package com.jeeplus.modules.guide.utils;

import com.alibaba.fastjson.JSONArray;
import com.jeeplus.common.json.AjaxJson;
import com.jeeplus.common.utils.DateUtils;
import com.jeeplus.common.utils.StringUtils;
import com.jeeplus.common.web.Result;
import com.jeeplus.modules.guide.entity.Company;
import com.jeeplus.modules.guide.model.query.ModAppointment;
import com.jeeplus.modules.guide.model.vo.ModAppointmentOut;
import com.jeeplus.modules.guide.service.AppointmentService;
import com.jeeplus.modules.guide.service.MobileIndexService;
import net.sf.json.JSONObject;
import okhttp3.*;
import org.junit.Test;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.http.HttpStatus;
import org.springframework.stereotype.Component;

import java.util.List;

/**
 * 法人数据同步http请求处理处理工具类
 *
 * @author azj
 * @date 2020-05-18/下午1:43:15
 */
@Component
public class CompanyUtils {
    private static final Logger logger = LoggerFactory.getLogger(CompanyUtils.class);
    @Autowired
    MobileIndexService mobileIndexService;
    @Autowired
    AppointmentService appointmentService;
    //第三方token
    @Value("${companyUrl}")
    private String companyUrl;
    public void getCompanyData(){
        Integer pageSize = 1000;Integer pageNum = 1;
        String result = doCompanyData(companyUrl, pageSize, pageNum);
        String doTime = DateUtils.getDateCount();
        if(StringUtils.isNotBlank(result)){
            JSONObject json = JSONObject.fromObject(result).getJSONObject("data");
            Integer totalRow = json.getInt("total");
            // 总页数
            int totalPage = (totalRow - 1) / pageSize + 1;
            try{
                List <Company> list = JSONArray.parseArray(json.getString("rows"),Company.class);
                mobileIndexService.insertCompany(list,doTime);
                for(int i=2;i<=totalPage;i++){
                    result = doCompanyData(companyUrl, pageSize, i);
                    json = JSONObject.fromObject(result).getJSONObject("data");
                    list = JSONArray.parseArray(json.getString("rows"),Company.class);
                    mobileIndexService.insertCompany(list,doTime);
                    if(i == totalPage){
                        mobileIndexService.delCompany(doTime);
                        list.clear();
                    }
                }
            }catch (Exception e){
                logger.error("更新企业信息失败！回滚数据。");
                mobileIndexService.backCompany(doTime);
            }

        }

    }

    public String doCompanyData(String url,Integer pageSize,Integer pageNum){
        OkHttpClient client = new OkHttpClient().newBuilder()
                .build();
        MediaType mediaType = MediaType.parse("application/json");
        RequestBody body = RequestBody.create(mediaType, "{\"paramsMap\": {\"pageSize\":"+pageSize+",\"pageNum\":"+pageNum+"}}");
        Request request = new Request.Builder()
                .url(url)
                .method("POST", body)
                .addHeader("sign", "Z3hjeXB0")
                .addHeader("encrypt", "yp91NtlX4Yc7EAYWJjoNCJ353w6Dc5sMo6q6WzDPX/cu+Kil0KYyp4ZkSjdn3jFD	")
                .addHeader("Content-Type", "application/json")
                .build();
        try{
            Response response = client.newCall(request).execute();
            return response.body().string().toString();
        }catch (Exception e){
            return "";
        }

    }

    //住房积分预约同步
    public void getGAWJF(){
        OkHttpClient client = new OkHttpClient().newBuilder()
                .build();
        Request request = new Request.Builder()
                .url("http://10.1.235.43/jzzjf/bookingInterface/getBookingInfo?code=510109&beginDate="+DateUtils.getDate()+"&endDate="+DateUtils.getDate())
                .method("GET", null)
                .build();
        try{
            Response response = client.newCall(request).execute();
            net.sf.json.JSONArray datas = JSONObject.fromObject(response.body().string().toString()).getJSONArray("datas");
            if(datas.size() >= 1){
                for(int k = 0;k<datas.size();k++){
                    if("1".equals(datas.getJSONObject(k).getString("type"))){
                        String bookingTime = datas.getJSONObject(k).getString("bookingTime");
                        ModAppointment mt = new ModAppointment();
                        mt.setBusinessId("9A71FB03-49EE-4F90-87C1-A25056A0C64C");
                        mt.setSysNo("5101090000008");
                        mt.setTime(datas.getJSONObject(k).getString("bookingDate"));
                        mt.setTimePeriod(Integer.parseInt(bookingTime.substring(0,bookingTime.indexOf("点"))));
                        mt.setSysName("成都市居住证积分");
                        mt.setMatterId("");
                        appointmentService.saveAppointment(mt, true, datas.getJSONObject(k).getString("idCard"), datas.getJSONObject(k).getString("phone"), datas.getJSONObject(k).getString("name"));
                    }
                }
            }
        }catch (Exception e){
        }
    }
}
